const App = getApp();
const pageIndex = 'category/list::';

Page({
  data: {
    // 搜索框样式
    searchColor: "rgba(0,0,0,0.4)",
    searchSize: "15",
    searchName: "搜索商品",
    // 列表高度
    scrollHeight: 0,

    // 一级分类：指针
    curNav: true,
    curIndex: 0,

    // 分类列表
    list: [],

    // show
    notcont: false,
    items:[],
    mainActiveIndex: 0,
    activeId: null,

    scrollHeight: null,

    showView: false, // 列表显示方式

    sortType: 'all', // 排序类型
    sortPrice: false, // 价格从低到高

    option: {}, // 当前页面参数
    shoplist: {}, // 商品列表数据

    no_more: false, // 没有更多数据
    isLoading: true, // 是否正在加载中

    page: 1, // 当前页码
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(option) {
    let _this = this;
    // 设置商品列表高度
    _this.setListHeight();
    // 记录option
    _this.setData({
      option
    });
    //获取分类列表
    this.getItems()
    _this.getCategoryList();
    // 设置列表显示方式
    _this.setShowView();
    // 获取商品列表
    _this.getGoodsList();
  },
  /**
   * 设置分类列表高度
   */
  setListHeight() {
    let _this = this;
    wx.getSystemInfo({
      success: function(res) {
        _this.setData({
          scrollHeight: res.windowHeight - 47,
        });
      }
    });
  },

  /**
   * 设置默认列表显示方式
   */
  setShowView() {
    let _this = this;
    _this.setData({
      showView: wx.getStorageSync(pageIndex + 'showView') || false
    });
  },
  format(arr) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].child) {
            arr[i].child = this.format(arr[i].child);
        }
        arr[i].child && (arr[i].children = arr[i].child);
        arr[i].name && (arr[i].text = arr[i].name);
        arr[i].category_id && (arr[i].id = arr[i].category_id);
        delete arr[i].child;
        delete arr[i].name;
        delete arr[i].category_id;
    }
    //返回新的数组格式
    return arr;
  },
 /**
   * 获取分类列表
   */
  getCategoryList() {
    let _this = this;
    App._get('category/index', {}, result => {
      let data = result.data;
      _this.setData({
        list: data.list,
        templet: data.templet,
        curNav: data.list.length > 0 ? data.list[0].category_id : true,
        notcont: !data.list.length
      });
    });
  },

  /**
   * 一级分类：选中分类
   */
  selectNav(e) {
    let _this = this;
    _this.setData({
      curNav: e.target.dataset.id,
      curIndex: parseInt(e.target.dataset.index),
      scrollTop: 0
    });
  },

  /**
   * 设置分享内容
   */
  onShareAppMessage() {
    let _this = this;
    return {
      title: _this.data.templet.share_title,
      path: '/pages/category/index?' + App.getShareUrlParams()
    };
  },
/**
   * 获取分类列表
   * @param {bool} isPage 是否分页
   * @param {number} page 指定的页码
   */
  getItems() {
    let _this = this;
    App._get('category/index', {}, result => {
      let resList = result.data.list;
        // arr为后端返回的数组格式
        _this.setData({
          items: this.format(resList),
        });
    });
  },
  /**
   * 获取商品列表
   * @param {bool} isPage 是否分页
   * @param {number} page 指定的页码
   */
  getGoodsList(isPage, page) {
    let _this = this;
    App._get('goods/lists', {
      page: page || 1,
      sortType: this.data.sortType,
      sortPrice: this.data.sortPrice ? 1 : 0,
      category_id: this.data.option.category_id || 0,
      search: this.data.option.search || '',
    }, result => {
      let resList = result.data.list,
        full_free = result.data.full_free,
        shoplist = _this.data.shoplist;
      if (isPage == true) {
        _this.setData({
          'shoplist.data': shoplist.data.concat(resList.data),
          full_free: full_free,
          isLoading: false,
        });
      } else {
        _this.setData({
          shoplist: resList,
          full_free: full_free,
          isLoading: false,
        });
      }
    });
  },

  /**
   * 设置商品列表高度
   */
  setListHeight() {
    let _this = this;
    wx.getSystemInfo({
      success: res => {
        _this.setData({
          scrollHeight: res.windowHeight - 90,
        });
      }
    });
  },

  /**
   * 切换排序方式
   */
  switchSortType(e) {
    let _this = this,
      newSortType = e.currentTarget.dataset.type,
      newSortPrice = newSortType === 'price' ? !this.data.sortPrice : true;

    this.setData({
      shoplist: {},
      isLoading: true,
      page: 1,
      sortType: newSortType,
      sortPrice: newSortPrice
    }, () => {
      // 获取商品列表
      _this.getGoodsList();
    });
  },

  /**
   * 切换列表显示方式
   */
  onChangeShowState() {
    let _this = this,
      showView = !_this.data.showView;
    wx.setStorageSync(pageIndex + 'showView', showView);
    _this.setData({
      showView
    });
  },

  /**
   * 下拉到底加载数据
   */
  bindDownLoad() {
    // 已经是最后一页
    if (this.data.page >= this.data.shoplist.last_page) {
      this.setData({
        no_more: true
      });
      return false;
    }
    // 加载下一页列表
    this.getGoodsList(true, ++this.data.page);
  },

  /**
   * 设置分享内容
   */
  onShareAppMessage() {
    // 构建分享参数
    return {
      title: "全部分类",
      path: "/pages/category/index?" + App.getShareUrlParams()
    };
  },

  /**
   * 商品搜索
   */
  triggerSearch() {
    let pages = getCurrentPages();
    // 判断来源页面
    if (pages.length > 1 &&
      pages[pages.length - 2].route === 'pages/search/index') {
      wx.navigateBack();
      return;
    }
    // 跳转到商品搜索
    wx.navigateTo({
      url: '../search/index',
    })
  },
  /**
   * 弹出类别选择弹窗
   */
  onTypeSelectShow() {
    let _this = this;
    _this.setData({
      typeSelectShow: !_this.data.typeSelectShow
    });
  },
  handleNavClick({ detail = {} }) {
    console.log("触发")
    console.log(detail)
    this.setData({
      mainActiveIndex: detail.index || 0
    });
  },
  handleItemClick({ detail = {} }) {
    console.log("触发2")
    console.log(detail)
    let _this = this;
    this.setData({
      'option.category_id':detail.id,
      activeId: detail.id,
      typeSelectShow: !_this.data.typeSelectShow
    });
    this.getGoodsList()
  },
  
  /**
   * 确认购买弹窗
   */
  onToggleTrade(e) {
    this.selectComponent("#gotushop").modShow(e.currentTarget.id);
  },
  

});